from os import listdir
import os
from PIL import Image

from tif.tif import to_tiff


def get_tiles_info(path):
    cols = [int(x) for x in listdir(path)]
    cols.sort()
    x1 = min(cols)  # x最小值
    x2 = max(cols)  # x最大值
    col_count = len(cols)  # 列数

    pics = listdir(path + os.sep + str(cols[0]))
    pic_type = pics[0][pics[0].find(".") + 1:]

    rows = [int(x[0: x.find(".")]) for x in pics]
    rows.sort()
    row_count = len(rows)  # 行数
    y1 = min(cols)  # y最小值
    y2 = max(cols)  # y最大值

    return {
        'x1': x1,
        'x2': x2,
        'y1': y1,
        'y2': y2,
        'cols': cols,
        'rows': rows,
        'col_count': col_count,
        'row_count': row_count,
        'pic_type': pic_type
    }


def create_jpg(src_path, level):
    """
    从文件夹自动合并所有的切片
    :param src_path: 到z级别的路径
    :param level: 使用合成的切片等级
    :return: 合并后图片的路径
    """
    print("开始合成")
    print(src_path, level)
    base_path = src_path + os.sep + str(level)
    tile_info = get_tiles_info(base_path)
    print(tile_info)

    # 合并图片
    # #
    # # 图片转化为相同的尺寸
    ims = []
    for row in tile_info['rows']:
        ims_row = []
        for col in tile_info['cols']:
            image = Image.open(base_path + os.sep + str(col) + os.sep + str(row) + "." + tile_info['pic_type'])
            if image.mode != "RGB":
                image = image.convert('RGB')
            ims_row.append(image)

        ims.append(ims_row)

    #  单幅图像尺寸
    width, height = ims[0][0].size
    #
    # # 创建空白长图
    result = Image.new(ims[0][0].mode, (width * tile_info['col_count'], height * tile_info['row_count']))

    # # 拼接图片
    for i, row in enumerate(ims):
        for j, cell in enumerate(row):
            result.paste(cell, box=(j * width, i * height))

    # # 保存图片，只能为png格式，
    save_path = src_path + os.sep + 'res1.png'
    result.save(save_path)

    return to_tiff(save_path, tile_info['x1'], tile_info['y1'], level, tile_info['col_count'])



